// pages/handle/index.js
const storageService = require('../../../services/storage')
import {
  Toast
} from 'tdesign-miniprogram';

function isEmpty(value) {
  return (value == null || value == undefined || value.length == 0);
}

function isEmptyObj(obj) {
  return (obj == null || obj == undefined || Object.keys(obj).length === 0);
}

// 获取 App 实例
const appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    did: null,
    curTab: 'handle',
    tabs: [{
        value: 'device',
        label: '自动',
        icon: '/images/icons/auto_0.png'
      },
      {
        value: 'handle',
        label: '手动',
        icon: '/images/icons/handle_1.png'
      },
      {
        value: 'set',
        label: '设置',
        icon: '/images/icons/set_0.png'
      },
    ],
    handCfg: {},
    deviceCfg: {},

    autoRun: 0,
    longtap: false,
    showWithInput: false,
    modeName: "",
    switchVal: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.data.did = options.did;
    let autoRunCfg =  storageService.getAutoRunCfg(this.data.did)
    this.setData({
      autoRun: isEmptyObj(autoRunCfg) ? 0 : autoRunCfg.sRun
    });
    let dobj = storageService.getDeviceInfo(options.did)
    this.data.deviceCfg = dobj;
    this.getAndInitChs();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const $t = this;
    wx.$event.on(this.data.deviceCfg.topicSub, this, (obj) => {
      if (obj.type == "status") {
        if ($t.data.autoRun != obj.msg.sRun) {
          $t.setData({
            autoRun: obj.msg.sRun
          });
        }
      }
    });
  },
  onGoHome() {
    wx.redirectTo({
      url: "/pages/index/index",
    });
  },
  onTabChange(e) {
    let v = e.detail.value;
    if ("handle" == v) {
      return;
    }
    let url = "/packageB/pages/" + v + "/index?did=" + this.data.did;
    wx.redirectTo({
      url: url
    });
  },
  getAndInitChs() {
    let handCfg = storageService.getHandCfg(this.data.did)
    if (isEmptyObj(handCfg)) {
      let chCfg = storageService.getDeviceChannels(this.data.did)
      handCfg = {
        sel: 0,
        modes: [{
            "nm": "模式一",
            "cls": []
          },
          {
            "nm": "模式二",
            "cls": []
          }
        ]
      };
      for (var j = 0; j < handCfg.modes.length; j++) {
        let cls = handCfg.modes[j].cls;
        for (var i = 0; i < chCfg.length; i++) {
          if (chCfg[i].u == 0) {
            continue;
          }
          cls.push({
            "n": chCfg[i].n,
            "nm": chCfg[i].nm,
            "c": chCfg[i].c,
            "v": 0
          });
        }
      }
      storageService.saveHandCfg(this.data.did, handCfg)
    }
    this.setData({
      handCfg: JSON.parse(JSON.stringify(handCfg))
    });
    console.log(this.data.handCfg);
  },
  sliderChange(e) {
    if (this.valChange(e)) {
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
      this.sendValChgMsg(e);
    }
  },
  sliderChangeing(e) {
    this.valChange(e);
  },
  steppperChange(e) {
    if (this.valChange(e)) {
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
      this.sendValChgMsg(e);
    }
  },
  valChange(e) {
    if (this.data.autoRun == 1) {
      this.showToast("自动模式下无法手动调整!");
      return false;
    }
    if (this.data.handCfg.sel < 0) {
      this.showToast("请先选择模式!");
      return false;
    }
    const {
      value
    } = e.detail;
    let idx = e.currentTarget.dataset.idx;
    let str = "handCfg.modes[" + this.data.handCfg.sel + "].cls[" + idx + "].v";
    this.setData({
      [str]: value
    });
    return true;
  },
  sendValChgMsg(e) {
    const {
      value
    } = e.detail;
    let idx = e.currentTarget.dataset.idx;
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgVal", {
      n: this.data.handCfg.modes[this.data.handCfg.sel].cls[idx].n,
      v: value
    });
  },
  selMode(e) {
    if (this.data.longtap) {
      this.data.longtap = false;
      return;
    }
    let idx = e.currentTarget.dataset.idx;
    if (this.data.handCfg.sel == idx) {
      return;
    }
    this.setData({
      "handCfg.sel": idx
    });
    storageService.saveHandCfg(this.data.did, this.data.handCfg)
  },
  editModeName() {
    this.data.longtap = true;
    this.setData({
      showWithInput: true,
      modeName: this.data.handCfg.modes[this.data.handCfg.sel].nm
    });
  },
  editConfirm() {
    if (isEmpty(this.data.modeName)) {
      this.showToast("名称不能为空!");
      this.setData({
        modeName: this.data.handCfg.modes[this.data.handCfg.sel].nm
      });
      return;
    }
    let str = "handCfg.modes[" + this.data.handCfg.sel + "].nm";
    this.setData({
      [str]: this.data.modeName
    });
    storageService.saveHandCfg(this.data.did, this.data.handCfg)
    this.closeDialog();
  },
  closeDialog() {
    this.setData({
      showWithInput: false
    });
  },
  bindKeyInput: function (e) {
    let val = e.detail.value;
    if (isEmpty(val)) {
      val = "";
    }
    this.setData({
      modeName: val
    })
  },
  handAllOn() {
    if (this.data.autoRun == 1) {
      return;
    }
    let vArr = [];
    let cls = this.data.handCfg.modes[this.data.handCfg.sel].cls;
    for (var i = 0; i < cls.length; i++) {
      vArr.push({
        "n": cls[i].n,
        "v": cls[i].v
      });
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll1", vArr);
    this.showToast("命令已发送...");
  },
  handAllOff() {
    if (this.data.autoRun == 1) {
      return;
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll0", null);
    this.showToast("命令已发送...");
  },








  showToast(msg) {
    Toast({
      context: this,
      selector: '#t-toast',
      message: msg,
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.$event.remove(this.data.deviceCfg.topicSub, this);
  },
})